import {Component, OnInit} from '@angular/core';
import {Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {AlertService} from '../_services/alert.service';
import {AccountService} from '../_services/account.service';
import {User} from '../_models/user';

@Component({templateUrl: 'login.component.html'})
export class LoginComponent implements OnInit {
  form: FormGroup;
  loading = false;
  submitted = false;

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private accountService: AccountService,
    private alertService: AlertService
  ) {
  }

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  get f(): any {
    return this.form.controls;
  }

  onSubmit(): void {
    this.submitted = true;
    this.alertService.clear();
    if (this.form.invalid) {
      return;
    }
    this.loading = true;
    this.accountService.login(this.f.username.value, this.f.password.value)
      .subscribe({
        next: (resp) => {
          // console.log(resp.headers.keys());
          // console.log(resp.headers.get('authorization'));
          // get return url from query parameters or default to home page
          // const returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
            this.router.navigate(['/manage'], {
            queryParams: {
              name: resp.body.customer.name
            }
          }).then(r => { });
        },
        error: error => {
          this.alertService.error(error);
          this.loading = false;
        }
      });
  }
}
